package com.one.del;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.Contacts;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private static final int DIALOG_SELECT_CONTACT = 1;	
	
	private static final int DIALOG_SELECT_CALL_LOG = 2;	
	
	private static final int DIALOG_SINGLE_CHOICE = 3;
	
	
	private static final String[] PEOPLE_PROJECTION = new String[] {
		Contacts.People._ID, Contacts.People.PRIMARY_PHONE_ID,
		Contacts.People.TYPE, Contacts.People.NUMBER,
		Contacts.People.LABEL, Contacts.People.NAME, };
	
	private LinearLayout descLayout;
	
	private ListView listView;
	
	/**
	 * 记录选择项
	 */
	private boolean[] selects;
	
	/**
	 * 弹出窗，联系人名列表
	 */
	private String[] names;
	
	/**
	 * 通讯录列表
	 */
	private String[] callLogs;
	
	private  List<String> persons = new ArrayList<String>();
	
	private int delItemIndex = 0;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button del = (Button)this.findViewById(R.id.del);        
        Button btnContact = (Button)this.findViewById(R.id.btn_contact);
        Button btnCallLog = (Button)this.findViewById(R.id.btn_callLog);
        listView = (ListView)this.findViewById(R.id.personList);
        descLayout = (LinearLayout)this.findViewById(R.id.desc);
        
        del.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(persons==null || persons.isEmpty()){
					Toast.makeText(getApplicationContext(), "请先选择联系人！", Toast.LENGTH_LONG).show();
				}else{
					showDialog(DIALOG_SINGLE_CHOICE);
				}				
			}        	
        });       
       
        
        btnContact.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				showDialog(DIALOG_SELECT_CONTACT);
			}        	
        });        
        btnCallLog.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				showDialog(DIALOG_SELECT_CALL_LOG);	
			}        	
        });
    }    
    
    
    @Override
    protected Dialog onCreateDialog(int id) {
    	selectClear();
        switch (id) {       
        //通过选择联系人新增
        case DIALOG_SELECT_CONTACT:      	
        	
        	try{        		
        		//获取联系人数据
            	getContacts();
        		return new AlertDialog.Builder(MainActivity.this)
//              .setIcon(android.R.drawable.alert_dialog_icon)
              .setTitle(R.string.select_from_contact)
              .setMultiChoiceItems(names,selects,
                      new DialogInterface.OnMultiChoiceClickListener() {
                          public void onClick(DialogInterface dialog, int whichButton,
                                  boolean isChecked) {
                         	 selects[whichButton] = isChecked;
                          }
                      })
              .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                 	 //根据选择插入数据
                 	
                 	 insertBlackBySelect();
                 	 refresh();
                  }
              })
              .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                 	
                 	 refresh();
                  }
              })
             .create();
        	}catch(Exception e){
        		Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
        	}
        	 
        case DIALOG_SELECT_CALL_LOG:
        	
        	//获取通信记录
        	getCallLogs();
        	
        	return new AlertDialog.Builder(MainActivity.this)
//            .setIcon(R.drawable.alert_dialog_icon)
            .setTitle(R.string.select_from_callLog)
            .setMultiChoiceItems(callLogs,selects,
                    new DialogInterface.OnMultiChoiceClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton,
                                boolean isChecked) {
                       	 

                       	 selects[whichButton] = isChecked;
                        }
                    })
            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
               	 	//根据选择插入数据
                	
                	insertBlackByCallLog();
               	 	refresh();
                }
            })
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                
                	refresh();
                }
            })
           .create();   
        case DIALOG_SINGLE_CHOICE:
            return new AlertDialog.Builder(MainActivity.this)
//                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle("选择删除选项")
                .setSingleChoiceItems(R.array.delete_items, 0, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    	delItemIndex = whichButton;
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {                    	
                    	
                    	new DelThread(getApplicationContext(),persons,delItemIndex).start();			
    					Toast.makeText(getApplicationContext(), "删除成功！", Toast.LENGTH_LONG).show();
    					persons.clear();
    					refresh();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked No so do some stuff */
                    }
                })
               .create();
        }        	
        return null;
   }
    
    private void refresh(){
    	String[] selectPersons = new String[persons.size()];
    	
    	listView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, persons.toArray(selectPersons)));
    	if(selectPersons.length>0){
    		descLayout.setVisibility(View.GONE);
    	}else{
    		descLayout.setVisibility(View.VISIBLE);
    	}
   
    }
    
    /**
	 * 获取联系人数据
	 */
	private void getContacts(){				
		try{
			String orderBy = Contacts.People.NAME+" asc";
			Cursor c = this.getContentResolver().query(Contacts.People.CONTENT_URI, PEOPLE_PROJECTION, null,null , orderBy);
			selects = new boolean[c.getCount()];
			names = new String[c.getCount()];
			
			if(c!=null && c.moveToFirst()){
				int i = 0;
				while(!c.isAfterLast()){
					//数组赋值
					String tempName = c.getString(c.getColumnIndex(Contacts.People.NAME));	
					tempName=tempName==null?"":tempName;
					names[i] = 	tempName;
					i++;
					c.moveToNext();
				}
			}
			startManagingCursor(c);
			
		}catch(Exception e){
			Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
		}
		
	}
	
	private void getCallLogs(){
		LinkedHashSet<String> logSet = new LinkedHashSet<String>();
		Cursor c = this.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, CallLog.Calls.DATE+" desc");
		this.startManagingCursor(c);
		if(c.moveToFirst()){
			while(!c.isAfterLast()){
				String telName = c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));				
				String telNumber = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));
				if(telName == null){
					logSet.add(telNumber);
				}else{
					logSet.add(telName);
				}
				c.moveToNext();
			}
		}
		callLogs = new String[logSet.size()];
		logSet.toArray(callLogs);
		selects = new boolean[logSet.size()];
	}
	
	/**
	 * 根据选择的通信记录，插入到黑名单列表
	 */
	private void insertBlackByCallLog(){
		persons.clear();
		for(int i=0;i<selects.length;i++){
			if(selects[i]){
				persons.add(callLogs[i]);
			}
		}
	}
	
	
	private void insertBlackBySelect(){		
		persons.clear();
		for(int i=0;i<selects.length;i++){
			if(selects[i]){
				persons.add(names[i]);
			}
		}
	}
	
	private void selectClear(){
		if(selects != null && selects.length>0){
			for(int i=0;i<selects.length;i++){
				selects[i] = false;
			}
		}
		
	}
   
    
   
    
}